package org.budo.dubbo.protocol.async.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.budo.dubbo.protocol.async.BudoAsyncDubboProtocol;
import org.budo.dubbo.protocol.async.repository.AsyncRepository;
import org.springframework.util.StringUtils;

import com.alibaba.dubbo.rpc.Exporter;
import com.alibaba.dubbo.rpc.Invoker;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class DestinationUtil {
    public static List<String> destinations() {
        BudoAsyncDubboProtocol instance = BudoAsyncDubboProtocol.getInstance();
        if (null == instance) {
            log.error("#128 destinations, instance=" + instance);
            return null;
        }

        List<String> destinations = new ArrayList<String>();

        Collection<Exporter<?>> exporters = instance.getExporterMap().values();
        for (Exporter<?> exporter : exporters) {
            Invoker<?> invoker = exporter.getInvoker();
            String destinationName = DestinationUtil.getDestinationName(invoker);

            destinations.add(destinationName);
        }

        return destinations;
    }

    public static String getDestinationName(Invoker<?> invoker) {
        String destinationName = invoker.getUrl().getParameter(AsyncRepository.DESTINATION_NAME);
        if (!StringUtils.isEmpty(destinationName)) {
            return destinationName;
        }

        Class<?> interfaceType = invoker.getInterface();
        return "budo-async-" + interfaceType.getName();
    }
}